﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 客户管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class CustomermanagementService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Customermanagement> _customermanagementRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public CustomermanagementService(SqlSugarRepository<Customermanagement> customermanagementRep, ISqlSugarClient sqlSugarClient)
    {
        _customermanagementRep = customermanagementRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询客户管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询客户管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<CustomermanagementOutput>> Page(PageCustomermanagementInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _customermanagementRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.CustomerCode.Contains(input.Keyword) || u.CustomerName.Contains(input.Keyword) || u.Contact.Contains(input.Keyword) || u.ContactNumber.Contains(input.Keyword) || u.Email.Contains(input.Keyword) || u.CustomerAddress.Contains(input.Keyword) || u.Remark.Contains(input.Keyword) || u.AccountName.Contains(input.Keyword) || u.TaxpayerIdentificationNumber.Contains(input.Keyword) || u.BankAccount.Contains(input.Keyword) || u.BankDeposit.Contains(input.Keyword) || u.BankDepositAddrs.Contains(input.Keyword) || u.UploadAttachments.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerCode), u => u.CustomerCode.Contains(input.CustomerCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), u => u.CustomerName.Contains(input.CustomerName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactNumber), u => u.ContactNumber.Contains(input.ContactNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Email), u => u.Email.Contains(input.Email.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerAddress), u => u.CustomerAddress.Contains(input.CustomerAddress.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.AccountName), u => u.AccountName.Contains(input.AccountName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TaxpayerIdentificationNumber), u => u.TaxpayerIdentificationNumber.Contains(input.TaxpayerIdentificationNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BankAccount), u => u.BankAccount.Contains(input.BankAccount.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BankDeposit), u => u.BankDeposit.Contains(input.BankDeposit.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BankDepositAddrs), u => u.BankDepositAddrs.Contains(input.BankDepositAddrs.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UploadAttachments), u => u.UploadAttachments.Contains(input.UploadAttachments.Trim()))
            .WhereIF(input.Industry != null, u => u.Industry == input.Industry)
            .WhereIF(input.CustomerSourceId != null, u => u.CustomerSourceId == input.CustomerSourceId)
            .WhereIF(input.OrganizationId != null, u => u.OrganizationId == input.OrganizationId)
            .WhereIF(input.UserManagementId != null, u => u.UserManagementId == input.UserManagementId)
            .LeftJoin<Industry>((u, industry) => u.Industry == industry.Id)
            .LeftJoin<Customersource>((u, industry, customerSource) => u.CustomerSourceId == customerSource.Id)
            .LeftJoin<Organization>((u, industry, customerSource, organization) => u.OrganizationId == organization.Id)
            .LeftJoin<UserManagement>((u, industry, customerSource, organization, userManagement) => u.UserManagementId == userManagement.Id)
            .Select((u, industry, customerSource, organization, userManagement) => new CustomermanagementOutput
            {
                Id = u.Id,
                CustomerCode = u.CustomerCode,
                CustomerName = u.CustomerName,
                Industry = u.Industry,
                IndustryFkDisplayName = $"{industry.IndustryName}",
                CustomerSourceId = u.CustomerSourceId,
                CustomerSourceFkDisplayName = $"{customerSource.CustomerSourceName}",
                Contact = u.Contact,
                ContactNumber = u.ContactNumber,
                Email = u.Email,
                OrganizationId = u.OrganizationId,
                OrganizationFkDisplayName = $"{organization.OrganizationName}",
                UserManagementId = u.UserManagementId,
                UserManagementFkDisplayName = $"{userManagement.UserName}",
                State = u.State,
                CustomerAddress = u.CustomerAddress,
                Remark = u.Remark,
                AccountName = u.AccountName,
                TaxpayerIdentificationNumber = u.TaxpayerIdentificationNumber,
                BankAccount = u.BankAccount,
                BankDeposit = u.BankDeposit,
                BankDepositAddrs = u.BankDepositAddrs,
                UploadAttachments = u.UploadAttachments,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取客户管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取客户管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Customermanagement> Detail([FromQuery] QueryByIdCustomermanagementInput input)
    {
        return await _customermanagementRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加客户管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加客户管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddCustomermanagementInput input)
    {
        var entity = input.Adapt<Customermanagement>();
        return await _customermanagementRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新客户管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新客户管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateCustomermanagementInput input)
    {
        var entity = input.Adapt<Customermanagement>();
        await _customermanagementRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除客户管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除客户管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteCustomermanagementInput input)
    {
        var entity = await _customermanagementRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _customermanagementRep.FakeDeleteAsync(entity);   //假删除
        //await _customermanagementRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除客户管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除客户管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteCustomermanagementInput> input)
    {
        var exp = Expressionable.Create<Customermanagement>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _customermanagementRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _customermanagementRep.FakeDeleteAsync(list);   //假删除
        //return await _customermanagementRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataCustomermanagementInput input)
    {
        var industryData = await _customermanagementRep.Context.Queryable<Industry>()
            .InnerJoinIF<Customermanagement>(input.FromPage, (u, r) => u.Id == r.Industry)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.IndustryName}"
            }).ToListAsync();
        var customerSourceIdData = await _customermanagementRep.Context.Queryable<Customersource>()
            .InnerJoinIF<Customermanagement>(input.FromPage, (u, r) => u.Id == r.CustomerSourceId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerSourceName}"
            }).ToListAsync();
        var organizationIdData = await _customermanagementRep.Context.Queryable<Organization>()
            .InnerJoinIF<Customermanagement>(input.FromPage, (u, r) => u.Id == r.OrganizationId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.OrganizationName}"
            }).ToListAsync();
        var userManagementIdData = await _customermanagementRep.Context.Queryable<UserManagement>()
            .InnerJoinIF<Customermanagement>(input.FromPage, (u, r) => u.Id == r.UserManagementId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "industry", industryData },
            { "customerSourceId", customerSourceIdData },
            { "organizationId", organizationIdData },
            { "userManagementId", userManagementIdData },
        };
    }
    
    /// <summary>
    /// 导出客户管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出客户管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageCustomermanagementInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportCustomermanagementOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "客户管理导出记录");
    }
    
    /// <summary>
    /// 下载客户管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载客户管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportCustomermanagementOutput>(), "客户管理导入模板", (_, info) =>
        {
            if (nameof(ExportCustomermanagementOutput.IndustryFkDisplayName) == info.Name) return _customermanagementRep.Context.Queryable<Industry>().Select(u => $"{u.IndustryName}").Distinct().ToList();
            if (nameof(ExportCustomermanagementOutput.CustomerSourceFkDisplayName) == info.Name) return _customermanagementRep.Context.Queryable<Customersource>().Select(u => $"{u.CustomerSourceName}").Distinct().ToList();
            if (nameof(ExportCustomermanagementOutput.OrganizationFkDisplayName) == info.Name) return _customermanagementRep.Context.Queryable<TreeParentOutput>().Select(u => $"{u.OrganizationName}").Distinct().ToList();
            if (nameof(ExportCustomermanagementOutput.UserManagementFkDisplayName) == info.Name) return _customermanagementRep.Context.Queryable<UserManagement>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入客户管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入客户管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportCustomermanagementInput, Customermanagement>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 行业
                    var industryLabelList = pageItems.Where(x => x.IndustryFkDisplayName != null).Select(x => x.IndustryFkDisplayName).Distinct().ToList();
                    if (industryLabelList.Any()) {
                        var industryLinkMap = _customermanagementRep.Context.Queryable<Industry>().Where(u => industryLabelList.Contains($"{u.IndustryName}")).ToList().ToDictionary(u => $"{u.IndustryName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Industry = industryLinkMap.GetValueOrDefault(e.IndustryFkDisplayName ?? "");
                            if (e.Industry == null) e.Error = "行业链接失败";
                        });
                    }
                    // 链接 客户来源
                    var customerSourceIdLabelList = pageItems.Where(x => x.CustomerSourceFkDisplayName != null).Select(x => x.CustomerSourceFkDisplayName).Distinct().ToList();
                    if (customerSourceIdLabelList.Any()) {
                        var customerSourceIdLinkMap = _customermanagementRep.Context.Queryable<Customersource>().Where(u => customerSourceIdLabelList.Contains($"{u.CustomerSourceName}")).ToList().ToDictionary(u => $"{u.CustomerSourceName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.CustomerSourceId = customerSourceIdLinkMap.GetValueOrDefault(e.CustomerSourceFkDisplayName ?? "");
                            if (e.CustomerSourceId == null) e.Error = "客户来源链接失败";
                        });
                    }
                    // 链接 销售部门
                    var organizationIdLabelList = pageItems.Where(x => x.OrganizationFkDisplayName != null).Select(x => x.OrganizationFkDisplayName).Distinct().ToList();
                    if (organizationIdLabelList.Any()) {
                        var organizationIdLinkMap = _customermanagementRep.Context.Queryable<TreeParentOutput>().Where(u => organizationIdLabelList.Contains($"{u.OrganizationName}")).ToList().ToDictionary(u => $"{u.OrganizationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.OrganizationId = organizationIdLinkMap.GetValueOrDefault(e.OrganizationFkDisplayName ?? "");
                            if (e.OrganizationId == null) e.Error = "销售部门链接失败";
                        });
                    }
                    // 链接 销售人员
                    var userManagementIdLabelList = pageItems.Where(x => x.UserManagementFkDisplayName != null).Select(x => x.UserManagementFkDisplayName).Distinct().ToList();
                    if (userManagementIdLabelList.Any()) {
                        var userManagementIdLinkMap = _customermanagementRep.Context.Queryable<UserManagement>().Where(u => userManagementIdLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.UserManagementId = userManagementIdLinkMap.GetValueOrDefault(e.UserManagementFkDisplayName ?? "");
                            if (e.UserManagementId == null) e.Error = "销售人员链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Customermanagement>>();
                    
                    var storageable = _customermanagementRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.CustomerCode?.Length > 32, "客户编码长度不能超过32个字符")
                        .SplitError(it => it.Item.CustomerName?.Length > 32, "客户名称长度不能超过32个字符")
                        .SplitError(it => it.Item.Contact?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.ContactNumber?.Length > 32, "联系电话长度不能超过32个字符")
                        .SplitError(it => it.Item.Email?.Length > 32, "电子邮箱长度不能超过32个字符")
                        .SplitError(it => it.Item.CustomerAddress?.Length > 100, "客户地址长度不能超过100个字符")
                        .SplitError(it => it.Item.Remark?.Length > 200, "备注长度不能超过200个字符")
                        .SplitError(it => it.Item.AccountName?.Length > 100, "账户名称长度不能超过100个字符")
                        .SplitError(it => it.Item.TaxpayerIdentificationNumber?.Length > 200, "纳税人识别号长度不能超过200个字符")
                        .SplitError(it => it.Item.BankAccount?.Length > 32, "银行账户长度不能超过32个字符")
                        .SplitError(it => it.Item.BankDeposit?.Length > 32, "开户银行长度不能超过32个字符")
                        .SplitError(it => it.Item.BankDepositAddrs?.Length > 32, "开户行地址长度不能超过32个字符")
                        .SplitError(it => it.Item.UploadAttachments?.Length > 1000, "上传附件长度不能超过1000个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
